<template>
  <div>
    <el-dialog title="新增支行" :visible.sync="showAddBranchDialog" center width="700px">
      <el-form :model="branchData" :rules="rules" ref="branchData">

        <el-form-item label="支行名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="branchData.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="状态" :label-width="formLabelWidth">
          <!-- label为选定时候的值 -->
          <el-radio v-model="branchData.status" :label="0">停用</el-radio>
          <el-radio v-model="branchData.status" :label="1">启用</el-radio>
        </el-form-item>

        <el-form-item label="所属主行" :label-width="formLabelWidth" prop="bank_id">
          <el-select v-model="branchData.bank_id" placeholder="选择所属主行">
            <el-option
              v-for="(item,index) in branchData.bankData"
              :key="index"
              :label="item.name"
              :value="item.bank_id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button type="primary" @click="submitBranch('branchData')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import store from '@/store'
  import {add} from '@/api/thk/cms/bankBranch'

  export default {
    name: 'addBranch',
    data() {
      return {
        showAddBranchDialog: false,
        formLabelWidth: '130px',
        branchData: {
          name: '',
          status: 1,
          bank_id: '',
          bankData: []
        },

        rules: {
          // 主行名字必须
          name:[
            { required: true, message: '请输入支行名称', trigger: 'blur' },
          ],
          bank_id: [
            { required: true, message: '请选择所属主行', trigger: 'change' }
          ],

        }

      }
    },


    methods: {
      // 判断是否点击了提交
      submitBranch(branchData){
        this.$refs[branchData].validate((valid) => {
          if (valid) {
            // 发送请求之前将bankData的数据删除,bankData只用于回显,并不需要实际发送到服务器
            delete this.branchData.bankData
            add(store.getters.token,this.branchData).then(result => {
              // 增加成功
              this.showAddBranchDialog = !this.showAddBranchDialog
              this.$parent.getBranchData()
            }).catch(error => {
              console.log(error)
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });

      },

      cancelDialog(bankData){
        // 将bankData设置到branchData中,用于选择所属主行时的数据回显
        this.branchData.bankData = bankData
        this.showAddBranchDialog = !this.showAddBranchDialog
      }



    }
  }
</script>
